package com.idbk.chargestation.activity.charge;


import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.R;
import com.idbk.chargestation.api.APIForCharge;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonChargeRefresh;
import com.idbk.chargestation.bean.JsonPileTariff;
import com.idbk.chargestation.bean.JsonPointPile;
import com.idbk.chargestation.bean.JsonQrScan;
import com.idbk.chargestation.dialog.DialogBill;
import com.idbk.chargestation.dialog.DialogResult;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.CheckUtil;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.view.DynamicWave;

import java.util.Locale;

/**
 * 当前充电：直流充电桩（DC）
 *
 * @author lupc, zhx
 */
public class ActivityChargingDc extends BaseActivity implements OnClickListener {

    public final static String TAG = ActivityChargingDc.class.getSimpleName();
    /**
     * 数据刷新时间
     */
    public final static int INTERVAL_DATA_REFRESH = 5000;

    public final static String KEY_CHARGE_ACTION = "key_charge_action";
    /**
     * 操作：等待启动
     */
    public final static int CHARGE_ACTION_WAIT = 0;
    /**
     * 操作：已启动
     */
    public final static int CHARGE_ACTION_CHARGING = 1;
    /**
     * BMS电压参数 1：表示12V，2：表示24V
     */
    private final static int VOLTAGE_BNS_12 = 1;
    private final static int VOLTAGE_BNS_24 = 2;
    private Context mContext;

    private TextView mTextChargeAuto, mTextChargeCustom, mTextChargeStop;

    private ImageView mImageLayerMask, mImageLayerInner, mImageLayerOuter;
    private ImageView mImageLayerBubble1, mImageLayerBubble2;

    //提示
    private TextView mTextChargeTip;
    //消费金额，已充电量
    private TextView mTextCost, mTextElectric;
    //速度
    private TextView mTextChargeSpeed;
    //电压、电流
    private TextView mTextVolt, mTextCurrent;
    //电价
    private TextView mTextElectricPrice;
    //分时电价
    private TextView mTextChargeTimePrice;
    //服务费
    private TextView mTextServicePrice, mTexServiceUnit;
    //当前充电模式
    private TextView mTextChargeMode;

    /**
     * 自定义破浪控件
     */
    private DynamicWave mImageLayerBubbleWave;

    /**
     * 破浪控件中的百分比数值
     */
    private TextView mTextChargeValue;

    /**
     * 当前充电百分比
     */
    private int mChargePercent = 0;

    /**
     * 标志位：是否在刷新
     */
    private boolean mFlagIsRefreshing = false;

    /**
     * 标志位：当前是否在充电
     */
    private boolean mFlagIsCharging = false;


    private String mPileSn;

    private String mGunNum;

    private ProgressDialog mPDialog;

    /**
     * 枪选择界面传进来的数据
     */
    private JsonQrScan mQrScanData;
    /**
     * 充电的资费策略
     */
    public JsonPileTariff mChargeTariff;
    private int mCount = 0;
    private DialogResult mDialog;
    private DialogBill mBill;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_charging_dc);

        setupView();

        setupData();
    }

    private void setupView() {
        mContext = this;
        //速度
        mTextChargeSpeed = (TextView) findViewById(R.id.textview_charge_speed);
        //电压 电流
        mTextVolt = (TextView) findViewById(R.id.voltage);
        mTextCurrent = (TextView) findViewById(R.id.current);
        //
        mTextCost = (TextView) findViewById(R.id.textview_cost);
        mTextElectric = (TextView) findViewById(R.id.textview_electricity);
        //
        mTextChargeTip = (TextView) findViewById(R.id.textview_charge_tip);
        //电费
        mTextElectricPrice = (TextView) findViewById(R.id.textview_charge_electricit_price);

        //分时电价
        mTextChargeTimePrice = (TextView) findViewById(R.id.textview_charge_time_price);
        mTextChargeTimePrice.setOnClickListener(this);
        mTextServicePrice = (TextView) findViewById(R.id.textview_charge_service_price);
        mTexServiceUnit = (TextView) findViewById(R.id.service_price_unit);
        //当前充电模式
        mTextChargeMode = (TextView) findViewById(R.id.textview_charge_mode);


        mImageLayerMask = (ImageView) findViewById(R.id.iamgeview_dc_layer_mask);
        mImageLayerInner = (ImageView) findViewById(R.id.iamgeview_dc_layer_inner_ring);
        mImageLayerOuter = (ImageView) findViewById(R.id.iamgeview_dc_layer_outer_ring);
        mImageLayerBubble1 = (ImageView) findViewById(R.id.iamgeview_dc_layer_bubble1);
        mImageLayerBubble2 = (ImageView) findViewById(R.id.iamgeview_dc_layer_bubble2);

        mImageLayerBubbleWave = (DynamicWave) findViewById(R.id.iamgeview_dc_layer_wave);

        mTextChargeValue = (TextView) findViewById(R.id.textview_charge_value);

        //返回
        findViewById(R.id.toolbar_back).setOnClickListener(this);

        //自动充满
        mTextChargeAuto = (TextView) findViewById(R.id.textview_charge_auto_full);
        //自定义充电
        mTextChargeCustom = (TextView) findViewById(R.id.textview_charge_custom);
        //停止充电
        mTextChargeStop = (TextView) findViewById(R.id.textview_charge_stop);
        if (mTextChargeAuto != null && mTextChargeCustom != null && mTextChargeStop != null) {
            mTextChargeAuto.setOnClickListener(this);
            mTextChargeCustom.setOnClickListener(this);
            mTextChargeStop.setOnClickListener(this);
        }

        setCurrentChargeValue(0);
    }

    private void setupData() {
        int action = getIntent().getIntExtra(KEY_CHARGE_ACTION, -1);
        if (action == CHARGE_ACTION_CHARGING) {
            //绑定基本数据
            mPileSn = getIntent().getStringExtra("pileSn");
            mGunNum = String.format(Locale.CHINA, "%02d", getIntent().getIntExtra("gunNum", 1));

            //第一次进来时候 资费还不知道
            setupTariffView(null);

            //速度
            mTextChargeSpeed.setText("直流(枪" + mGunNum + ")");

            //开始刷新
            startChargeRefresh();
        } else if (action == CHARGE_ACTION_WAIT) {
            //等待启动充电
            mQrScanData = getIntent().getParcelableExtra(JsonQrScan.KEY);
            if (mQrScanData == null) {
                Toast.makeText(this, "缺少必要的参数！", Toast.LENGTH_SHORT).show();
                finish();
            }

            //绑定基本数据
            mPileSn = mQrScanData.pileSn;
            mGunNum = String.format(Locale.CHINA, "%02d", getIntent().getIntExtra("gunNum", 1));

            //速度
            mTextChargeSpeed.setText("直流(枪" + mGunNum + ")");

            //显示资费相关的信息
            if (mQrScanData != null) {
                setupTariffView(mQrScanData.tariff);
            } else {
                setupTariffView(null);
            }

            //是否是分时电价
            if (mQrScanData.priceTypeEnum == JsonPointPile.PRICE_TYPE_TIME) {
                mChargeTariff = mQrScanData.tariff;
                mTextChargeTimePrice.setVisibility(View.VISIBLE);
            } else {
                mTextChargeTimePrice.setVisibility(View.GONE);
            }

            stopChargeRefresh();
        } else {
            Toast.makeText(this, "缺少必要的参数！", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void setupTariffView(JsonPileTariff tariff) {
        if (tariff == null) {
            mTextElectricPrice.setText("未知");
            mTextChargeTimePrice.setVisibility(View.GONE);
            mTextServicePrice.setText("未知");
            return;
        }

        //电费+单位
        String mCurrentPrice = tariff.compareTime();
        mTextElectricPrice.setText(mCurrentPrice);

        //是否是分时电价
        mTextChargeTimePrice.setVisibility(View.VISIBLE);

        mTextServicePrice.setText(tariff.getServicePrice());
        String unit = tariff.getServiceUnit();
        mTexServiceUnit.setText(unit);
    }

    private void setCurrentChargeValue(int value) {
        if (value < 0 || value > 100) {
            Log.w(TAG, "电量必须在0-100%之间！");
            return;
        }
        //设置 电量值
        String str = value + "%";
        SpannableString span = new SpannableString(str);
        span.setSpan(new AbsoluteSizeSpan(60, true), 0, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.WHITE), 0, str.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new AbsoluteSizeSpan(20, true), str.length() - 1, str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.WHITE), str.length() - 1, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTextChargeValue.setText(span);

        //停止水泡和波浪动画
        mImageLayerBubbleWave.clearAnimation();
        mImageLayerBubble1.clearAnimation();
        mImageLayerBubble2.clearAnimation();

        //遮罩层的高度
        int heightMask = mImageLayerMask.getHeight();

        //当前数值时刻 波浪的高度
        int height = (int) (heightMask * value / 100d);

        //更改波浪高度
        mImageLayerBubbleWave.setCurrentValue(value);

        //水浪和水泡开始新的动画
        Log.d(TAG, "遮罩高度：" + mImageLayerMask.getHeight() + "px， 遮罩宽度：" + mImageLayerMask.getWidth());
        Log.d(TAG, "波浪高度：" + mImageLayerMask.getHeight() + "px， 波浪宽度：" + mImageLayerMask.getWidth());

        //水泡1的动画
        int heightBubble1 = mImageLayerBubble1.getHeight();
        ObjectAnimator ani = ObjectAnimator
                .ofFloat(mImageLayerBubble1, "translationY", heightBubble1, heightBubble1 - height)
                .setDuration(4000);
        ani.setRepeatCount(-1);
        ani.start();

        //水泡2动画
        int heightBubble2 = mImageLayerBubble2.getHeight();
        ani = ObjectAnimator
                .ofFloat(mImageLayerBubble1, "translationY", heightBubble2, heightBubble2 - height)
                .setDuration(8000);
        ani.setRepeatCount(-1);
        ani.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.textview_charge_auto_full:
                chargeAutoFull();
                break;
            case R.id.textview_charge_custom:
                chargeCustom();
                break;
            case R.id.textview_charge_stop:
                stopCharge();
                break;
            case R.id.textview_charge_time_price:
                showTimePrice();
                break;
            default:
                break;
        }
    }

    //显示分时电价
    private void showTimePrice() {
        if (mChargeTariff != null) {
            View view = getLayoutInflater().inflate(R.layout.pop_pile_time_price, new LinearLayout(this), false);
            TextView textview = (TextView) view.findViewById(R.id.textview_pile_time_price);
            String str = mChargeTariff.timePrices();
            textview.setText(CheckUtil.textFromHtml(str));
            view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
            int popupWidth = view.getMeasuredWidth();
            PopupWindow mPop = new PopupWindow(
                    view,
                    LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            mPop.setFocusable(true);
            mPop.setOutsideTouchable(true);
            // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
            mPop.setBackgroundDrawable(new PaintDrawable(Color.TRANSPARENT));

            int[] location = new int[2];
            mTextChargeTimePrice.getLocationOnScreen(location);
            mPop.showAtLocation(
                    mTextChargeTimePrice,
                    Gravity.NO_GRAVITY,
                    (location[0] + mTextChargeTimePrice.getWidth() / 2) - popupWidth / 2,
                    location[1] + mTextChargeTimePrice.getHeight());
        }
    }

    private void chargeCustom() {
        Intent intent = new Intent(this, ActivityCustomCharge.class);
        intent.putExtra(JsonQrScan.KEY, mQrScanData);
        startActivityForResult(intent, ActivityChargingAc.REQUEST_CODE);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //如果还在充电，则启动 刷新
        if (mFlagIsCharging && !mFlagIsRefreshing) {
            startChargeRefresh();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        //如果还在充电 且 还在刷新，则停止 刷新
        if (mFlagIsCharging && mFlagIsRefreshing) {
            stopChargeRefresh();
        }
    }


    /**
     * 启动 充电动画和数据刷新
     */
    private void startChargeRefresh() {
        mFlagIsRefreshing = true;

        //启动 数据刷新
        mTextChargeValue.postDelayed(mChargeStateRefresh, 0);
        //启动动画
        LinearInterpolator interpolator = new LinearInterpolator();
        //外层 顺时针 旋转
        Animation animClockwise = AnimationUtils.loadAnimation(this, R.anim.alternate_image_clockwise);
        animClockwise.setInterpolator(interpolator);
        mImageLayerOuter.setBackgroundResource(R.drawable.ani_charging_box_outer_ring);
        mImageLayerOuter.startAnimation(animClockwise);
        //内存 逆时针 旋转
        Animation animAntiClockwise = AnimationUtils.loadAnimation(this, R.anim.alternate_image_anticlockwise);
        animAntiClockwise.setInterpolator(interpolator);
        mImageLayerInner.startAnimation(animAntiClockwise);

        //其他UI显示
        mTextChargeStop.setVisibility(View.VISIBLE);
        mTextChargeAuto.setVisibility(View.GONE);
        mTextChargeCustom.setVisibility(View.GONE);

        //当前充电模式
        mTextChargeMode.setVisibility(View.VISIBLE);
    }

    /**
     * 停止 充电动画和数据刷新
     */
    private void stopChargeRefresh() {
        mFlagIsRefreshing = false;
        //移除 数据刷新
        mTextChargeValue.removeCallbacks(mChargeStateRefresh);
        //停止动画
        setCurrentChargeValue(mChargePercent);
        mImageLayerOuter.clearAnimation();
        mImageLayerInner.clearAnimation();

        //其他UI显示
        mTextChargeStop.setVisibility(View.GONE);
        mTextChargeAuto.setVisibility(View.VISIBLE);
        mTextChargeCustom.setVisibility(View.VISIBLE);
        mImageLayerOuter.setBackgroundResource(R.drawable.bg_charging_box_dc_background_mask);

        mTextChargeTip.setText("已连接车辆，等待启动充电");

        //当前充电模式
        mTextChargeMode.setVisibility(View.GONE);
        mTextVolt.setText("0.0");
        mTextCurrent.setText(R.string.zero_decimals_two);
        mTextElectric.setText(R.string.zero_decimals_two);
        mTextCost.setText(R.string.zero_decimals_two);
    }

    /**
     * 刷新回调
     */
    private Runnable mChargeStateRefresh = new Runnable() {

        @Override
        public void run() {
            APIForCharge.refreshCharge(mPileSn, mGunNum, mResponseRefresh);
        }
    };

    /**
     * 刷新请求的结果
     */
    private EHttpResponse mResponseRefresh = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonChargeRefresh result = GsonUtils.toBean(JsonChargeRefresh.class, response);
            if (result == null) {
                mTextChargeTip.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                mTextChargeTip.setText("获取服务器数据为空");
                mTextChargeTip.setTextColor(Color.rgb(255, 0, 0));
                mTextChargeValue.postDelayed(mChargeStateRefresh, INTERVAL_DATA_REFRESH);
            } else if (result.status == GlobalResult.OK.getStatus()) {
                if (result.getGunState() == JsonPointPile.STATUS_CHARGING) {
                    mFlagIsCharging = true;
                    if (result.SOC != mChargePercent) {
                        mChargePercent = result.SOC;
                        setCurrentChargeValue(mChargePercent);
                    }
                    if (result.priceTypeEnum == JsonPointPile.PRICE_TYPE_TIME) {
                        mTextChargeTimePrice.setVisibility(View.VISIBLE);
                    } else {
                        mTextChargeTimePrice.setVisibility(View.GONE);
                    }
                    bindData(result);
                    mTextChargeValue.postDelayed(mChargeStateRefresh, INTERVAL_DATA_REFRESH);

                } else if (result.getGunState() == JsonPointPile.STATUS_WAIT) {
                    mTextChargeTip.setText("等待充电中");
                    mTextChargeValue.postDelayed(mChargeStateRefresh, INTERVAL_DATA_REFRESH);

                } else if (result.getGunState() == JsonPointPile.STATUS_OFFLINE) {
                    if (mCount >= 4) {
                        stopChargeRefresh();
                        chargeStateDialog("充电提示", "稍后请到->我的钱包 查看账单");

                    } else {
                        mCount++;
                        mTextChargeValue.postDelayed(mChargeStateRefresh, INTERVAL_DATA_REFRESH);
                    }
                } else {
                    stopChargeRefresh();
                    chargeStateDialog("充电结束", "稍后请到->我的钱包 查看账单");
                }

            } else if (result.status == GlobalResult.CHARGE_FINISH_OK.getStatus()) {
                //其他一些界面操作
                mFlagIsCharging = false;
                stopChargeRefresh();
                showBillDialog(result);

            } else if (result.status == GlobalResult.CHARGE_FINISH_NETWORK.getStatus()) {
                //其他一些界面操作
                mFlagIsCharging = false;
                stopChargeRefresh();
                chargeStateDialog("充电结束", "网络延迟，稍后请到->我的钱包 查看账单");

            } else if (result.status == GlobalResult.TOKEN_INVALID.getStatus()
                    || result.status == GlobalResult.TOKEN_REQUIRED.getStatus()) {
                jumpToLogin(ActivityChargingDc.this, true);

            } else {
                chargeStateDialog("充电提示", result.message);
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Log.d(TAG, error.getMessage(), error.getCause());
            mTextChargeTip.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            mTextChargeTip.setText("无法获取服务器数据，请检查当前网络");
            mTextChargeTip.setTextColor(Color.rgb(255, 0, 0));
            mTextChargeValue.postDelayed(mChargeStateRefresh, INTERVAL_DATA_REFRESH);
        }

        @Override
        public void onEFinish() {
            dismissMyProgressDialog();
            //关闭 等待窗S
        }
    };


    private void stopCharge() {
        mTextChargeValue.removeCallbacks(mChargeStateRefresh);
        mPDialog = new ProgressDialog(this);
        mPDialog.setCancelable(false);
        mPDialog.setMessage("正在请求停止充电...");
        mPDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mMainRequest != null) {
                    mMainRequest.cancel();
                }
                mTextChargeValue.post(mChargeStateRefresh);
            }
        });
        mPDialog.show();
        mPDialog.setCanceledOnTouchOutside(false);
        mMainRequest = APIForCharge.stopCharge(mPileSn, mGunNum, mResponseStopCharge);
    }

    /**
     * 停止充电请求的结果
     */
    private EHttpResponse mResponseStopCharge = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonChargeRefresh result = GsonUtils.toBean(JsonChargeRefresh.class, response);
            if (result == null) {
                Toast.makeText(mContext, "数据返回错误！", Toast.LENGTH_SHORT).show();
                return;
            }
            if (result.status == GlobalResult.OK.getStatus()) {
                //绑定数据
                //其他一些界面操作
                mFlagIsCharging = false;
                stopChargeRefresh();
                //实时充电服务费用为serverMoney  停止充电服务费用为serviceMoney
                //这里serverMoney = serviceMoney是为了兼容showBillDialog无需重新再写
                result.serverMoney = result.serviceMoney;
                showBillDialog(result);

            } else if (result.status == GlobalResult.CHARGE_FINISH_NETWORK.getStatus()) {
                mFlagIsCharging = false;
                stopChargeRefresh();
                chargeStateDialog("充电结束", "网络延迟，稍后请到->我的钱包 查看账单");

            } else if (result.status == GlobalResult.CHARGE_FINISH_STOP.getStatus()) {
                mTextChargeValue.removeCallbacks(mChargeStateRefresh);
                stopChargeRefresh();
                chargeStateDialog("充电结束", "充电已完成,请到->我的钱包 查看账单");

            } else {
                Toast.makeText(mContext, result.message, Toast.LENGTH_SHORT).show();
                mTextChargeValue.post(mChargeStateRefresh);
            }

        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Toast.makeText(mContext, "无法连接到服务器！", Toast.LENGTH_SHORT).show();
            mTextChargeValue.post(mChargeStateRefresh);
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            if (mPDialog != null) {
                mPDialog.dismiss();
            }
        }

    };

    private void chargeAutoFull() {
        new AlertDialog.Builder(mContext)
                .setTitle("请选择您爱车的BMS电压参数")
                .setCancelable(false)
                .setSingleChoiceItems(new String[]{"12V", "24V"}, 0, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        int bms = VOLTAGE_BNS_12;
                        if (which == 1) {
                            bms = VOLTAGE_BNS_24;
                        }
                        showMyProgressDialog(true, false, "请求中...");
                        mMainRequest = APIForCharge.startCharge(
                                mPileSn,
                                JsonPointPile.CHARGE_FINISH_BY_AUTO + "",
                                null,
                                mGunNum,
                                bms,
                                mResponseFullCharge);
                    }
                })
                .setNegativeButton(R.string.common_cancel, null)
                .create()
                .show();
    }

    /**
     * 自动充满请求的结果
     */
    private EHttpResponse mResponseFullCharge = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonChargeRefresh result = GsonUtils.toBean(JsonChargeRefresh.class, response);
            if (result == null) {
                Toast.makeText(mContext, "数据返回错误！", Toast.LENGTH_SHORT).show();
                return;
            }
            if (result.status == GlobalResult.OK.getStatus()) {
                //绑定数据
                bindData(result);

                //其他一些界面操作
                mFlagIsCharging = true;
                startChargeRefresh();
            } else {
                Toast.makeText(mContext, result.message, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Toast.makeText(mContext, R.string.common_tip_resultnull, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            dismissMyProgressDialog();
        }

    };

    /**
     * 将数据与控件进行绑定
     */
    private void bindData(JsonChargeRefresh data) {
        //电压 电流
        mTextVolt.setText(String.format(Locale.CHINA, "%.2f", data.voltage));
        mTextCurrent.setText(String.format(Locale.CHINA, "%.2f", data.current));
        //
        mTextCost.setText(String.format(Locale.CHINA, "%.2f", (data.chargeMoney + data.serverMoney)));
        mTextElectric.setText(String.format(Locale.CHINA, "%.2f", data.quantity));

        if (mChargePercent != data.SOC) {
            setCurrentChargeValue(mChargePercent);
        }

        mTextChargeTip.setText(String.format(Locale.CHINA, "正在充电，已充%d分钟，充满预计需要%d分钟", data.finishTime, data.remainTime));
        mTextChargeTip.setTextColor(ContextCompat.getColor(ActivityChargingDc.this, R.color.tj_text_content_6));

        //显示资费相关的数据
        mChargeTariff = data.tariff;
        setupTariffView(data.tariff);

        //充电模式
        mTextChargeMode.setText(getChargeMethodSpan(data.chargeMethod, data.chargeLimit));
    }

    private void chargeStateDialog(String mTitle, String msg) {
        if (isFinishing()) {
            return;
        }
        if (mBill == null && mDialog == null) {
            mDialog = new DialogResult(ActivityChargingDc.this, true, mTitle, msg);
            mDialog.show();
            mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (mBill != null) {
                        mBill.dismiss();
                    }
                    Intent intent = getIntent();
                    setResult(ActivityChargeList.RESPONSE_CODE, intent);
                    finish();
                }
            });
        }
    }

    public void showBillDialog(JsonChargeRefresh refresh) {
        if (isFinishing()) {
            return;
        }
        if (mDialog == null && mBill == null) {
            mBill = new DialogBill(ActivityChargingDc.this, refresh);
            mBill.show();
            mBill.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    Intent intent = getIntent();
                    setResult(ActivityChargeList.RESPONSE_CODE, intent);
                    finish();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //判断返回结果
        if (requestCode == ActivityChargingAc.REQUEST_CODE &&
                resultCode == RESULT_OK) {
            final int mIntMethod = data.getIntExtra("mMethod", -1);
            final int mIntLimit = data.getIntExtra("mSelect", -1);
            if (mIntMethod != -1 && mIntLimit != -1) {
                new AlertDialog.Builder(mContext)
                        .setTitle("请选择您爱车的BMS电压参数")
                        .setCancelable(false)
                        .setSingleChoiceItems(new String[]{"12V", "24V"}, 0, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                int bms = VOLTAGE_BNS_12;
                                if (which == 1) {
                                    bms = VOLTAGE_BNS_24;
                                }
                                showMyProgressDialog(true, false, "请求中...");
                                mMainRequest = APIForCharge.startCharge(
                                        mPileSn,
                                        mIntMethod + "",
                                        mIntLimit + "",
                                        mGunNum,
                                        bms,
                                        mResponseFullCharge);
                            }
                        })
                        .setNegativeButton(R.string.common_cancel, null)
                        .create()
                        .show();

            }
        }

    }


    public final static String STR_CHARGE_MODE_AUTO = "当前模式：自动充满";

    public final static String STR_CHARGE_MODE_MONEY = "当前模式：按金额充电(%d元)";

    public final static String STR_CHARGE_MODE_TIME = "当前模式：按时间充电(%d分钟)";

    public final static String STR_CHARGE_MODE_ENERGY = "当前模式：按电量充电(%d度)";

    public static SpannableString getChargeMethodSpan(int mode, int value) {
        SpannableString span;
        switch (mode) {
            case JsonPointPile.CHARGE_FINISH_BY_AUTO:
                span = new SpannableString(STR_CHARGE_MODE_AUTO);
                span.setSpan(new AbsoluteSizeSpan(13, true), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.rgb(102, 102, 102)), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //
                span.setSpan(new AbsoluteSizeSpan(14, true), 5, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.BLACK), 5, 9, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            case JsonPointPile.CHARGE_FINISH_BY_ENERGY:
                span = new SpannableString(String.format(Locale.CHINA, STR_CHARGE_MODE_ENERGY, value));
                span.setSpan(new AbsoluteSizeSpan(13, true), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.rgb(102, 102, 102)), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //
                span.setSpan(new AbsoluteSizeSpan(14, true), 5, 11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.BLACK), 5, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //
                span.setSpan(new AbsoluteSizeSpan(14, true), 11, span.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.rgb(241, 162, 37)), 11, span.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //
                span.setSpan(new AbsoluteSizeSpan(14, true), span.length() - 1, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.BLACK), span.length() - 1, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            case JsonPointPile.CHARGE_FINISH_BY_MONEY:
                span = new SpannableString(String.format(Locale.CHINA, STR_CHARGE_MODE_MONEY, value));
                span.setSpan(new AbsoluteSizeSpan(13, true), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.rgb(102, 102, 102)), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //
                span.setSpan(new AbsoluteSizeSpan(14, true), 5, 11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.BLACK), 5, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //
                span.setSpan(new AbsoluteSizeSpan(14, true), 11, span.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.rgb(241, 162, 37)), 11, span.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //
                span.setSpan(new AbsoluteSizeSpan(14, true), span.length() - 1, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.BLACK), span.length() - 1, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            case JsonPointPile.CHARGE_FINISH_BY_TIME:
                span = new SpannableString(String.format(Locale.CHINA, STR_CHARGE_MODE_TIME, value));
                span.setSpan(new AbsoluteSizeSpan(13, true), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.rgb(102, 102, 102)), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //
                span.setSpan(new AbsoluteSizeSpan(14, true), 5, 11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.BLACK), 5, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //
                span.setSpan(new AbsoluteSizeSpan(14, true), 11, span.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.rgb(241, 162, 37)), 11, span.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //
                span.setSpan(new AbsoluteSizeSpan(14, true), span.length() - 1, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new ForegroundColorSpan(Color.BLACK), span.length() - 1, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            default:
                span = new SpannableString("当前模式：未知");
                break;
        }
        return span;
    }

}
